<?php

/**
 * This is the model class for table "marcaciones".
 *
 * The followings are the available columns in table 'marcaciones':
 * @property integer $id_marcacion
 * @property integer $id
 * @property string $tipo_marcacion
 * @property string $tiempo
 *
 * The followings are the available model relations:
 * @property Profesores $id0
 * @property Clases[] $clases
 */
class Marcaciones extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'marcaciones';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('id, tipo_marcacion', 'required'),
			array('id', 'numerical', 'integerOnly'=>true),
			array('tipo_marcacion', 'length', 'max'=>3),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id_marcacion, id, tiempo', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'id0' => array(self::BELONGS_TO, 'Profesores', 'id'),
			'clases' => array(self::MANY_MANY, 'Clases', 'marcaciones_clases(id_marcacion, id_clase)'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id_marcacion' => 'Marcación',
			'id' => 'Profesor',
			'tipo_marcacion' => 'Tipo',
			'tiempo' => 'Fecha y hora marcada',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id_marcacion',$this->id_marcacion);
		$criteria->compare('id',$this->id);
		$criteria->compare('tipo_marcacion',$this->tipo_marcacion,true);
		$criteria->compare('tiempo',$this->tiempo,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'sort'=>array('defaultOrder'=>'tiempo DESC'),
		));
	}

	public function searchById($id)
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id_marcacion',$this->id_marcacion);
		$criteria->compare('id',$id);
		$criteria->compare('tipo_marcacion',$this->tipo_marcacion,true);
		$criteria->compare('tiempo',$this->tiempo,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'sort'=>array('defaultOrder'=>'tiempo DESC'),
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Marcaciones the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * Realiza acciones antes de guardar el model.
	 * @return boolean true si se puede guardar, false en caso contrario.
	 */
	protected function beforeSave()
	{
		if (parent::beforeSave() == false) return false;
		return true;
	}

	/**
	 * Realiza acciones después de haber guardado exitosamente el model.
	 */
	protected function afterSave()
	{   
	    parent::afterSave();
	  
		$last = marcaciones::model()->find(array('order'=>'tiempo DESC'));	
		$mtime = $last->tiempo;
		$mhora = $this->generarHora($mtime);
		$mdate = $this->generarDia($mtime);
	 	//echo $mhora."<br>".$mdate."<br>".$mtime; 
	
	if($this->filtroasistencia($mhora,$mdate)){
	  	
	  	$fechaAhora = new CDbExpression('NOW()');   
	    $model = new asistencias;
	    $model->id = $this->id;
	    $model->fecha = $fechaAhora;
	    $model->asistencia_total = 50;
	   	$model->asistencia_requerida = 2000000;
	  	$model->ausencias = 0;
	   	$model->save();

	  }
	}

		protected function generarHora($mtime)
	{
		return Yii::app()->dateFormatter->format('HH:mm:ss', $mtime);
	}

	protected function generarDia($mtime)
	{
		return Yii::app()->dateFormatter->format('yyyy-MM-dd', $mtime);
	}

	protected function filtroasistencia($mhora,$mdate)
	{

			if($this->tipo_marcacion == 'S')
			{
				//$post = Clases::model()->find('id=:post_id', array(':post_id'=>1));
				$clases = Clases::model()->findAllByAttributes(array('id'=>3));
					//array('order' => 'hora_inicio ASC'));
				
				//foreach ( $clases as $clase) 
			//	{
					//echo $mdate.'<pre>'; 
					$start_date = $mdate;
					$end_date = date("Y-m-d",strtotime($mdate."+1 month"));
					$end_date = date("Y-m-d",strtotime($end_date."-1 day"));
					$aux_date = $start_date;
 					
					while (strtotime($aux_date) <= strtotime($end_date)) {
						
						if(strtotime($end_date) != strtotime($aux_date))
							{			
							$aux_date = date("Y-m-d",strtotime($aux_date."+1 day"));
								echo '<br>'.$aux_date;

							}else{
								echo '<br>'.$aux_date;
								break;
							}
					}
				//}

				//echo '<pre>';
				//var_dump($clases);
				//echo '</pre>';

				//$hentrada = Clases::model()->find(array('order'=>'hora_inicio ASC'));	
				//print_r($hentrada);
				//echo '</pre>'.$hentrada->hora_inicio



			return TRUE; 
		}

	}

}
   
	